/**
 * 
 */
package com.roshan.web.security.context;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;

import com.roshan.web.security.service.ICookieService;

@Component
public class RoarSecurityContextRepository implements SecurityContextRepository {

    @Autowired
    private ICookieService cookieService;

    private @Value("${roar.security.cookie.name}")
    String securityCookieName;

    @Override
    public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {

        HttpServletRequest request = requestResponseHolder.getRequest();
        RoarSecurityContext roarSecurityContext = (RoarSecurityContext) this.cookieService
                .retrieveCookiePersistedObject(this.securityCookieName, request);

        if (roarSecurityContext != null && roarSecurityContext.getAuthentication() != null) {

            return roarSecurityContext;
        }

        return SecurityContextHolder.createEmptyContext();
    }

    @Override
    public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
        // security context persisting logic is not handled here.
    }

    @Override
    public boolean containsContext(HttpServletRequest request) {

        Cookie securityContextCookie = this.cookieService.retrieveCookie(this.securityCookieName, request);
        return securityContextCookie != null && securityContextCookie.getMaxAge() != 0;
    }

}
